package com.ruoyi.combat.util.weibo;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
public class WeiboApi {

    @Autowired
    private RedisCache redisCache;

    public static String getAccessToken() {
       /* Collection<String> keys = redisCache.keys(CacheConstants.WEIBO_DATA_KEY + "*");
        Object cacheObject = redisCache.getCacheObject(CacheConstants.WEIBO_DATA_KEY + "access_token");
        return String.valueOf(cacheObject);*/
        return "2.00XeMLzGgFvjfD1da06009c50ugiM6";
    }

    public Response sendPost(String url, RequestBody formBody) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.weibo.com/2/statuses/update.json")
                .post(formBody)
                .build();
        return client.newCall(request).execute();
    }

    public static Response sendPost1(String url, RequestBody formBody) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.weibo.com/2/statuses/update.json")
                .post(formBody)
                .build();
        return client.newCall(request).execute();
    }

    /**
     *
     */
    public static String upLoadImg() throws IOException {
        String url = "https://c.api.weibo.com/2/statuses/upload_pic/biz.json";

        String token = getAccessToken();
        Map data = new HashMap();
        data.put("access_token", token);
//        data.put("pic", );

        return "";
    }


    /**
     * 发布微博
     *
     * @param status
     * @return
     * @throws IOException
     */
    public static String postWeibo(String status, String token) throws IOException {
//        String url = "https://c.api.weibo.com/2/statuses/update/biz.json";
        String url = "https://api.weibo.com/2/statuses/share.json";
        String is_longtext = "0";
        if (status.length() >= 140) {
            is_longtext = "1";
        }
        RequestBody formBody = new FormBody.Builder()
//                .add("access_token", getAccessToken())
                .add("access_token", token)
                .add("status", status)
//                .add("is_longtext", is_longtext)
//                .add("rip", status)
                .build();
        Response response = sendPost1(url, formBody);
        return response.body().string();
    }

    /**
     * 删除微博
     *
     * @param id
     * @return
     * @throws IOException
     */
    public String deleteWeibo(String id) throws IOException {
        String url = "https://c.api.weibo.com/2/statuses/destroy/biz.json";
        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("access_token", getAccessToken())
                .add("id", id)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public static String getUserId() {
        String token = "2.00hdVDxG0PpoPe9706dd7797BJCeIE";


        String url = "https://api.weibo.com/2/users/show.json?access_token=" + token + "&screen_name=" + "呼源招1982";

        String s = HttpUtil.get(url);
        System.out.println(s);
        return s;

    }

    public static void main1(String[] args) throws IOException {
        //https://api.weibo.com/2/statuses/user_timeline.json?access_token=2.00XeMLzG0aSPd715d718ba77ATzDUD&uid=6972663192&count=1
        String token = "2.00XeMLzGgFvjfD1da06009c50ugiM6";
        String s = getFriends("6369437425");
//        System.out.println(s);
//        s = getFriends("6400823737");
//        System.out.println(s);
//        s = getFriends("6972663192");
//        System.out.println(s);
//
////        String s = followUser("6972663192");
//
//        System.out.println(s);

//        String content = "阳光灿烂，春光明媚！";
//        String s = postWeibo(content, token);
//        System.out.println(s);


        //https://weibo.com/ajax/statuses/update


    }

    /**
     * 获取关注列表
     *
     * @param uid
     * @return
     * @throws IOException
     */
    public static String getFriends(String uid) throws IOException {
        OkHttpClient client = new OkHttpClient();

        String token = "2.00XeMLzGgFvjfD1da06009c50ugiM6";
        Request request = new Request.Builder()
                .url("https://api.weibo.com/2/friendships/friends.json?access_token=" + token + "&uid=" + uid)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    /**
     * 关注用户
     *
     * @param uid
     * @return
     * @throws IOException
     */
    public static String followUser(String uid) throws IOException {
        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("access_token", getAccessToken())
                .add("uid", uid)
                .build();

        Request request = new Request.Builder()
                .url("https://api.weibo.com/2/friendships/create.json")
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 取消关注用户
     *
     * @param uid
     * @return
     * @throws IOException
     */
    public String unfollowUser(String uid) throws IOException {
        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("access_token", getAccessToken())
                .add("uid", uid)
                .build();

        Request request = new Request.Builder()
                .url("https://api.weibo.com/2/friendships/destroy.json")
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    //获取最新微博
    public String getLatestWeibo(String userId) {
        String result = "";
        try {
            // 构建请求URL
            String urlString = "https://api.weibo.com/2/statuses/user_timeline.json?access_token=" + getAccessToken() + "&uid=" + userId + "&count=1";
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 发送请求并读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            // 输出最新微博内容
            System.out.println(content.toString());

            connection.disconnect();
            System.out.println("获取微博用户最新微博：*******************************");
            System.out.println(content);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) {
        String token = "2.00iotvYF0aSPd7d7b7aa435e0YF2md";
        String url = "https://api.weibo.com/2/statuses/share.json";

//将参数转为JSON才能转发到微博
        Map<String,Object> object = new HashMap();
        //获取rip的地址
        object.put("rip","123.52.16.238");
        //微博的token
        object.put("access_token",token);
        //文件上传
        object.put("pic",new File("C:\\Users\\HYZ\\Desktop\\图片\\006ZbcExgy1fmewpd71nmj30280280si.jpg"));
        //上传文件的内容
        object.put("status","美好的一天");

        String post = HttpUtil.post(url, object);


        System.out.println(post);


    }


}